package com.rzico.sbl.ui

import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import com.amap.api.AMapLocationHelper
import com.lzg.OkGoHelper
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityLoginBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.LoginViewModel
import com.tim.library.MessageNotification
import com.umeng.analytics.MobclickAgent
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showOneHintDialog
import com.xinnuo.common_ui.utils.subscribeBy
import com.xinnuo.objectbox.equalString
import com.xinnuo.objectbox.getBox
import com.xinnuo.objectbox.model.AppLoginData
import com.xinnuo.objectbox.model.AppLoginData_
import com.xinnuo.objectbox.model.UserLoginData
import com.xinnuo.objectbox.model.UserLoginData_
import org.json.JSONObject


class LoginActivity : BaseActivity(R.layout.activity_login) {

    private val mBinding by lazy { ActivityLoginBinding.bind(getRootView()) }

    private lateinit var mLoginMode: String
    private var mUid = ""

    override fun getViewModel() = get<LoginViewModel>()

    override fun initData() {
        setTransparentAndToolbar(isVisible = false)

        mLoginMode = getString("loginMode", "phone")

        // 设置checkBox选中框样式
        mBinding
            .loginCheck
            .setCompoundDrawable(
                R.drawable.login_agree_selector
            )

        // 检查登录方式
        getViewModel()
            .checkLoginMode(
                baseContext,
                mLoginMode,
                mBinding
            )

        // 检查登录状态
        checkState()
    }

    override fun initListener() {
        mBinding
            .apply {
                // 获取验证码
                btYzm.oneClick {
                    when {
                        loginAccount.rawText.isEmpty() -> {
                            loginAccount.requestFocus()
                            showToast("请输入手机号")
                            return@oneClick
                        }
                        !loginAccount.rawText.isMobile() -> {
                            loginAccount.requestFocus()
                            showToast("请输入正确的手机号")
                            return@oneClick
                        }
                    }

                    getViewModel()
                        .getPublicKey {
                            getViewModel()
                                .request(
                                    isLoadingBefore = false,
                                    requestUrl = BaseUrl.send_mobile,
                                    params = arrayOf(
                                        "mobile" to getViewModel().encrypt(loginAccount.rawText)
                                    ),
                                    onSuccess = {
                                        showToast("验证码发送成功！")
                                        getViewModel().countDown(count = 60)
                                            .bindLifeCycle(getLifecycleOwner())
                                            .subscribeBy(
                                                onNext = {
                                                    btYzm.text = "重新发送(${60 - it})"
                                                    btYzm.isClickable = false
                                                },
                                                onComplete = {
                                                    btYzm.text = "重新发送"
                                                    btYzm.isClickable = true
                                                }
                                            )
                                    }
                                )
                        }
                }

                // 密码显隐切换
                loginEye.oneClick {
                    when (it.getTag(R.id.empty_view) as String) {
                        "close" -> {
                            // 密码可见
                            loginPwd.transformationMethod =
                                HideReturnsTransformationMethod.getInstance()
                            loginPwd.setSelection(loginPwd.text.length)

                            loginEye.setImageResource(R.mipmap.login_eye_open)
                            loginEye.setTag(R.id.empty_view, "open")
                        }
                        else -> {
                            // 密码不可见
                            loginPwd.transformationMethod =
                                PasswordTransformationMethod.getInstance()
                            loginPwd.setSelection(loginPwd.text.length)

                            loginEye.setImageResource(R.mipmap.login_eye_close)
                            loginEye.setTag(R.id.empty_view, "close")
                        }
                    }
                }

                // 用户协议
                loginDeal
                    .oneClick {
                        startActivityEx<WebActivity>("title" to "用户协议")
                    }

                // 隐私政策
                loginSecret
                    .oneClick {
                        startActivityEx<WebActivity>("title" to "隐私政策")
                    }

                // 登录
                btLogin.oneClick {
                    when (mLoginMode) {
                        "account" -> {
                            when {
                                loginName.text.isBlank() -> {
                                    loginName.requestFocus()
                                    showToast("请输入账户号")
                                    return@oneClick
                                }
                                loginPwd.text.isBlank() -> {
                                    loginPwd.requestFocus()
                                    showToast("请输入密码")
                                    return@oneClick
                                }
                                loginPwd.text.length < 6 -> {
                                    loginPwd.requestFocus()
                                    showToast("密码长度不少于6位")
                                    return@oneClick
                                }
//                                !loginCheck.isChecked -> {
//                                    showToast("请同意并阅读协议和政策")
//                                    return@oneClick
//                                }
                            }

                            getViewModel()
                                .getPublicKey {
                                    window
                                        .decorView
                                        .post { loginWithAccount() }
                                }
                        }
                        else -> {
                            when {
                                loginAccount.rawText.isEmpty() -> {
                                    loginAccount.requestFocus()
                                    showToast("请输入手机号")
                                    return@oneClick
                                }
                                loginYzm.text.isBlank() -> {
                                    loginYzm.requestFocus()
                                    showToast("请输入验证码")
                                    return@oneClick
                                }
                                !loginAccount.rawText.isMobile() -> {
                                    loginAccount.requestFocus()
                                    showToast("请输入正确的手机号")
                                    return@oneClick
                                }
//                                !loginCheck.isChecked -> {
//                                    showToast("请同意并阅读协议和政策")
//                                    return@oneClick
//                                }
                            }

                            getViewModel()
                                .getPublicKey {
                                    window
                                        .decorView
                                        .post { login() }
                                }
                        }
                    }
                }

                // 切换登录方式
                loginSwitch.oneClick {
                    when (mLoginMode) {
                        "account" -> {
                            mLoginMode = "phone"

                            getViewModel()
                                .checkLoginMode(
                                    baseContext,
                                    mLoginMode,
                                    this
                                )
                        }
                        else -> {
                            mLoginMode = "account"

                            getViewModel()
                                .checkLoginMode(
                                    baseContext,
                                    mLoginMode,
                                    this
                                )
                        }
                    }
                }
            }
    }

    /**
     * 登录
     */
    private fun login() {
        val inputPhone = mBinding.loginAccount.rawText

        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                requestUrl = BaseUrl.login,
                params = arrayOf(
                    "mobile" to inputPhone,
                    "captcha" to getViewModel().encrypt(mBinding.loginYzm.content)
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    mUid = obj.optNotNull("uid")

                    putShared("loginMode", mLoginMode)
                    putShared("phone", inputPhone)
                    putShared("uid", mUid)
                    putShared("userId", obj.optNotNull("userId"))
                    putShared("userSign", obj.optNotNull("userSig"))

                    // 保存用户信息
                    getBox<UserLoginData>()
                        .apply {
                            val userInfo = query()
                                .equalString(UserLoginData_.uid, mUid)
                                .build()
                                .findFirst()
                                ?.also { item ->
                                    item.phone = inputPhone
                                    item.userId = obj.optNotNull("userId")
                                    item.userSign = obj.optNotNull("userSig")
                                }
                                ?: UserLoginData(
                                    phone = inputPhone,
                                    uid = mUid,
                                    userId = obj.optNotNull("userId"),
                                    userSign = obj.optNotNull("userSig")
                                )

                            put(userInfo)
                        }

                    // 保存登录信息
                    getBox<AppLoginData>()
                        .apply {
                            val appInfo = query()
                                .equalString(AppLoginData_.uid, mUid)
                                .build()
                                .findFirst()
                                ?.also { item -> item.phone = inputPhone }
                                ?: AppLoginData(
                                    uid = mUid,
                                    phone = inputPhone
                                )

                            put(appInfo)
                        }

                    OkGoHelper
                        .commonHeaders {
                            put("x-mid", getString("uid"))
                        }

                    window.decorView.post { getShopStatus() }
                }
            )
    }

    /**
     * 账号登录
     */
    private fun loginWithAccount() {
        val inputPhone = mBinding.loginName.content

        getViewModel()
            .request(
                isLoadingBefore = false,
                isLoadingAfter = false,
                isMultipart = true,
                requestUrl = BaseUrl.login2,
                params = arrayOf(
                    "username" to inputPhone,
                    "enPassword" to getViewModel().encrypt(mBinding.loginPwd.content)
                ),
                onSuccess = {
                    val obj = JSONObject(it)

                    mUid = obj.optNotNull("uid")

                    putShared("loginMode", mLoginMode)
                    putShared("phone", inputPhone)
                    putShared("uid", mUid)
                    putShared("userId", obj.optNotNull("userId"))
                    putShared("userSign", obj.optNotNull("userSig"))

                    // 保存用户信息
                    getBox<UserLoginData>()
                        .apply {
                            val userInfo = query()
                                .equalString(UserLoginData_.uid, mUid)
                                .build()
                                .findFirst()
                                ?.also { item ->
                                    item.phone = inputPhone
                                    item.userId = obj.optNotNull("userId")
                                    item.userSign = obj.optNotNull("userSig")
                                }
                                ?: UserLoginData(
                                    phone = inputPhone,
                                    uid = mUid,
                                    userId = obj.optNotNull("userId"),
                                    userSign = obj.optNotNull("userSig")
                                )

                            put(userInfo)
                        }

                    // 保存登录信息
                    getBox<AppLoginData>()
                        .apply {
                            val appInfo = query()
                                .equalString(AppLoginData_.uid, mUid)
                                .build()
                                .findFirst()
                                ?.also { item -> item.phone = inputPhone }
                                ?: AppLoginData(
                                    uid = mUid,
                                    phone = inputPhone
                                )

                            put(appInfo)
                        }

                    OkGoHelper
                        .commonHeaders {
                            put("x-mid", getString("uid"))
                        }

                    window.decorView.post { getShopStatus() }
                }
            )
    }

    /**
     * 获取店铺状态
     */
    private fun getShopStatus() {
        getViewModel()
            .request(
                isLoadingBefore = false,
                requestUrl = BaseUrl.shop,
                requestMethod = HttpMethod.GET,
                onSuccess = {
                    val obj = JSONObject(it)

                    val shopId = obj.optNotEmpty("shopId", "0")
                    val shopName = obj.optNotNull("shopName")
                    val shopStatus = obj.optNotNull("status")
                    val expireDay = obj.optInt("expire", 365)
                    val privacy = obj.optNotEmpty("privacyStatus", "on")
                    val callStatus = obj.optNotNull("callOrder")
                    val canRob = obj.optBoolean("rob")
                    val isOpen = !obj.optBoolean("paused")
                    val isReal = obj.optBoolean("hasRealName")

                    putShared("shopId", shopId)
                    putShared("shopName", shopName)
                    putShared("shopStatus", shopStatus)
                    putShared("expireDay", expireDay)     //过期天数
                    putShared("privacyStatus", privacy)   //号码隐私保护
                    putShared("incomeStatus", callStatus) //手机来电接单
                    putShared("canRob", canRob)           //是否抢单
                    putShared("isOpen", isOpen)           //是否营业
                    putShared("isReal", isReal)           //是否实名

                    reportEnable = obj.optBoolean("phEnable")     //是否报货
                    driverEnable = obj.optBoolean("driverEnable") //是否纯司机

                    // 店铺时间配置
                    val objTimeStr = obj.optNotEmpty("shippingConfig", "{}")
                    val objTime = JSONObject(objTimeStr)
                    val orderWarn = objTime.optNotNull("orderOvertime")
                    putShared("configJson", objTimeStr) //店铺时间配置
                    putShared("orderWarn", orderWarn)   //订单超时时间

                    // 角色属性
                    val objRole = obj.optJSONObject("roles") ?: JSONObject()
                    userRole = objRole.optNotNull("id")
                    roleName = objRole.optNotNull("name")

                    // 服务商属性
                    val objOperate = obj.optJSONObject("operate") ?: JSONObject()
                    serviceId = objOperate.optNotNull("id")
                    serviceStep = objOperate.optNotNull("step")

                    isLogin = true

                    // 保存用户信息
                    getBox<UserLoginData>()
                        .apply {
                            query()
                                .equalString(UserLoginData_.uid, mUid)
                                .build()
                                .findFirst()
                                ?.let { item ->
                                    item.shopId = shopId
                                    item.shopName = shopName
                                    item.shopStatus = shopStatus
                                    item.privacyStatus = privacy
                                    item.callTelStatus = callStatus.intValue
                                    item.canRob = canRob
                                    item.isOpen = isOpen
                                    item.isReal = isReal
                                    // 报货属性
                                    item.reportEnable = reportEnable
                                    item.driverEnable = driverEnable
                                    // 店铺时间配置
                                    item.expireDay = expireDay
                                    item.configJson = objTimeStr
                                    item.orderWarn = orderWarn
                                    // 角色属性
                                    item.userRole = objRole.optNotNull("id")
                                    item.roleName = objRole.optNotNull("name")
                                    // 服务商属性
                                    item.serviceId = objOperate.optNotNull("id")
                                    item.serviceStep = objOperate.optNotNull("step")

                                    put(item)
                                }
                        }

                    // 保存登录信息
                    getBox<AppLoginData>()
                        .apply {
                            query()
                                .equalString(AppLoginData_.uid, mUid)
                                .build()
                                .findFirst()
                                ?.let { item ->
                                    item.loginMode = mLoginMode
                                    item.isLogin = true

                                    put(item)
                                }
                        }

                    when (shopStatus) {
                        "success" ->
                            getInt("expireDay")
                                .also { rest ->
                                    when (rest) {
                                        1, 2, 3, 5, 10, 15 -> showHintDialog(rest)
                                        in 4..Int.MAX_VALUE -> mainPage()
                                        else -> showHintDialog(rest)
                                    }
                                }
                        else -> {
                            startActivityEx<OpenActivity>()

                            finishView()
                        }
                    }
                }
            )
    }

    private fun showHintDialog(day: Int) {
        showOneHintDialog(
            isForced = true,
            hint = when (day) {
                in 1..15 -> "您的账户还有${day}天即将到期，未避免影响正常使用，请联系服务商及时续费！"
                else -> "您的账户因欠费已停止服务，请联系服务商续费后恢复使用！"
            },
            onResult = {
                (day in 1..15).condition { mainPage() }
            }
        )
    }

    private fun mainPage() {
        startActivityEx<MainActivity>()

        finishView()
    }

    /**
     * 检查登录状态
     */
    private fun checkState() {
        val isOffLine = intent.getBooleanExtra("offLine", false)

        if (isOffLine) {
            // 清除shared缓存
            isLogin = false
            clearShared(
                "uid",
                "userId",
                "userSign",
                "userRole",
                "roleName",
                "shopId",
                "shopName",
                "shopStatus",
                "privacyStatus",
                "orderWarn",
                "configJson",
                "userRole",
                "roleName",
                "serviceId",
                "serviceStep"
            )
            putShared("canRob", false)
            putShared("isOpen", true)
            putShared("isReal", false)
            putShared("isLocation", false)

            // 清除登录状态
            getBox<AppLoginData>()
                .apply {
                    all.forEach {
                        it.isLogin = false
                        put(it)
                    }
                }

            // 清除请求头
            OkGoHelper
                .commonHeaders()
                .remove("x-mid")

            // 暂停定位
            AMapLocationHelper
                .getInstance(baseContext)
                .stopLocation()

            // 清除所有通知
            MessageNotification
                .getInstance(getIContext())
                .clearAll()

            // 友盟账号统计登出
            MobclickAgent.onProfileSignOff()

            // 关闭所有页面
            ActivityStack
                .screenManager
                .popAllActivityExcept(this::class.java)
        }
    }

}